package com.airobot.candidates.service.impl;

import com.airobot.candidates.entity.InterviewCandidates;
import com.airobot.candidates.entity.InterviewSchedule;
import com.airobot.candidates.entity.InterviewQuestion;
import com.airobot.candidates.mapper.CandidateMapper;
import com.airobot.candidates.mapper.InterviewScheduleMapper;
import com.airobot.candidates.mapper.InterviewQuestionMapper;
import com.airobot.candidates.service.CandidateService;
import com.example.common.utils.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Comparator;

/**
 * 候选人服务实现类
 * 处理面试相关的业务逻辑
 */
@Service
public class CandidateServiceImpl implements CandidateService {

    private static final Logger log = LoggerFactory.getLogger(CandidateServiceImpl.class);

    @Autowired
    private CandidateMapper candidateMapper;

    @Autowired
    private InterviewScheduleMapper interviewScheduleMapper;

    @Autowired
    private InterviewQuestionMapper questionMapper;

    /**
     * 获取面试详情
     * @param candidateId 候选人ID
     * @return 面试详情，包含面试安排、题目列表和面试官信息
     */
    @Override
    public CommonResult<Map<String, Object>> getInterviewDetails(Integer candidateId) {
        try {
            log.info("开始获取面试详情，候选人ID: {}", candidateId);
            
            // 获取候选人信息
            InterviewCandidates candidate = candidateMapper.selectById(candidateId);
            if (candidate == null) {
                return CommonResult.failed("未找到候选人信息");
            }
            log.info("获取到候选人信息: {}", candidate);

            // 获取面试安排
            List<InterviewSchedule> allSchedules = interviewScheduleMapper.selectList(null);
            log.info("所有面试安排: {}", allSchedules);
            
            // 获取最新的有效面试安排
            InterviewSchedule schedule = allSchedules.stream()
                .filter(s -> s.getCandidateId().equals(candidateId) && s.getStatus() == 1)
                .max(Comparator.comparing(InterviewSchedule::getCreatedAt))
                .orElse(null);
                
            if (schedule == null) {
                return CommonResult.failed("未找到有效的面试安排");
            }
            log.info("获取到面试安排: {}", schedule);

            // 获取题目集
            List<Integer> questionSetIds = schedule.getQuestionSetIds();
            log.info("面试安排的题目集IDs: {}", questionSetIds);
            
            if (questionSetIds != null && !questionSetIds.isEmpty()) {
                log.info("解析后的题目集IDs: {}", questionSetIds);
                List<InterviewQuestion> questions = questionMapper.getQuestionsBySetIds(questionSetIds);
                
                // 组装返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("schedule", schedule);
                result.put("questions", questions);
                result.put("interviewer", getInterviewerInfo(schedule.getDigitalInterviewerId()));
                
                log.info("成功获取面试详情: {}", result);
                return CommonResult.success(result);
            } else {
                return CommonResult.failed("未找到面试题目");
            }
        } catch (Exception e) {
            log.error("获取面试详情失败", e);
            return CommonResult.failed("获取面试详情失败: " + e.getMessage());
        }
    }

    /**
     * 完成面试
     * @param candidateId 候选人ID
     * @return 操作结果
     */
    @Override
    public CommonResult<String> completeInterview(Integer candidateId) {
        try {
            log.info("完成面试，候选人ID: {}", candidateId);
            
            // 获取候选人信息
            InterviewCandidates candidate = candidateMapper.selectById(candidateId);
            if (candidate == null) {
                return CommonResult.failed("未找到候选人信息");
            }

            // 检查面试状态
            if (candidate.getInterviewStatus() != 2) {
                log.info("完成面试失败，候选人ID: {}", candidateId);
                log.info("面试状态不正确，当前状态: {}", candidate.getInterviewStatus());
                return CommonResult.failed("面试状态不正确，当前状态: " + candidate.getInterviewStatus());
            }

            // 更新面试状态为已完成
            candidate.setInterviewStatus(3);
            candidateMapper.updateById(candidate);

            return CommonResult.success("面试已完成");
        } catch (Exception e) {
            log.error("完成面试失败", e);
            return CommonResult.failed("完成面试失败: " + e.getMessage());
        }
    }

    /**
     * 获取面试官信息
     * @param interviewerId 面试官ID
     * @return 面试官信息
     */
    private Map<String, Object> getInterviewerInfo(Long interviewerId) {
        try {
            // TODO: 调用面试官服务获取面试官信息
            Map<String, Object> interviewer = new HashMap<>();
            interviewer.put("id", interviewerId);
            interviewer.put("name", "数字人面试官");
            interviewer.put("avatar", "https://example.com/avatar.png");
            interviewer.put("description", "AI面试官");
            return interviewer;
        } catch (Exception e) {
            log.error("获取面试官信息失败", e);
            return null;
        }
    }

    /**
     * 开始面试
     * @param candidateId 候选人ID
     * @return 面试信息
     */
    @Override
    public CommonResult<Map<String, Object>> startInterview(Integer candidateId) {
        // TODO: 实现开始面试逻辑
        return CommonResult.failed("方法未实现");
    }

    /**
     * 根据手机号获取候选人信息
     * @param phone 手机号
     * @return 候选人信息
     */
    @Override
    public CommonResult<Map<String, Object>> getByPhone(String phone) {
        // TODO: 实现根据手机号获取候选人信息逻辑
        return CommonResult.failed("方法未实现");
    }

    /**
     * 获取面试安排
     * @param candidateId 候选人ID
     * @return 面试安排信息
     */
    @Override
    public CommonResult<Map<String, Object>> getInterviewSchedule(Integer candidateId) {
        // TODO: 实现获取面试安排逻辑
        return CommonResult.failed("方法未实现");
    }

    /**
     * 提交答案
     * @param candidateId 候选人ID
     * @param questionId 题目ID
     * @param answer 答案内容
     * @return 提交结果
     */
    @Override
    public CommonResult<String> submitAnswer(Integer candidateId, Integer questionId, String answer) {
        // TODO: 实现提交答案逻辑
        return CommonResult.failed("方法未实现");
    }

    /**
     * 根据手机号获取完整面试详情
     * @param phone 手机号
     * @return 完整面试详情
     */
    @Override
    public CommonResult<Map<String, Object>> getFullInterviewDetailByPhone(String phone) {
        // TODO: 实现根据手机号获取完整面试详情逻辑
        return CommonResult.failed("方法未实现");
    }
} 